package com.sam.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

@Component
public class JobTaskBuilder {

    @Value("${threadpool.core-pool-size:#{1}}")
    private int corePoolSize;

    @Value("${threadpool.max-pool-size:#{7}}")
    private int maxPoolSize;

    @Value("${threadpool.queue-capacity:#{1}}")
    private int queueCapacity;

    @Value("${threadpool.keep-alive-seconds:#{60}}")
    private int keepAliveSeconds;

    public ThreadPoolTaskExecutor buildJobTaskWorkerThreadPool(){
        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        // 空闲的多余线程最大存活时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("worker-");

        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //执行初始化
        executor.initialize();

        return executor;
    }

    public ThreadPoolTaskScheduler buildJobTaskScheduler(){
        ThreadPoolTaskScheduler schedulerExecutor = new ThreadPoolTaskScheduler();
        schedulerExecutor.setPoolSize(1);
        schedulerExecutor.setThreadNamePrefix("taskExecutor-");
        schedulerExecutor.setWaitForTasksToCompleteOnShutdown(false);

        //executor.setAwaitTerminationSeconds(60);

        schedulerExecutor.initialize();
        return schedulerExecutor;
    }
}
